package com.d.lib.ui.view.sort;

import com.d.lib.ui.view.LogUtil;
import java.util.*;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.utils.TextTool;

/**
 * SortUtil
 * Created by D on 2017/6/7.
 */
public class SortUtil {
  private List<SortBean> mDatas;
  private Map<String, int[]> mLetterMap;
  private int mLastFirstVisibleItem = -1;

  public void onScrolled(ListContainer recyclerView, Component layout, Text tvLetter) {
    try {


      if (recyclerView == null || layout == null || tvLetter == null || mLetterMap == null || mDatas == null) {
        return;
      }
      int firstVisibleItemPosition = recyclerView.getFirstVisibleItemPosition();
      LogUtil.debug("sort", "firstVisibleItemPosition: " + firstVisibleItemPosition);
      int[] value = mLetterMap.get(mDatas.get(firstVisibleItemPosition).letter);
      int nextSectionPosition = value != null ? value[1] : -1;

      if (nextSectionPosition == firstVisibleItemPosition + 1) {
        Component childView = recyclerView.getComponentAt(firstVisibleItemPosition);
        if (childView != null) {
          int titleHeight = layout.getHeight();
          int bottom = childView.getBottom();
          ComponentContainer.LayoutConfig params = layout.getLayoutConfig();
          if (bottom < titleHeight) {
            float pushedDistance = bottom - titleHeight;
            params.setMarginTop((int) pushedDistance);
            layout.setLayoutConfig(params);
          } else {
            if (params.getMarginTop() != 0) {
              params.setMarginTop(0);
              layout.setLayoutConfig(params);
            }
          }
        }
      }
      if (firstVisibleItemPosition != mLastFirstVisibleItem) {
        ComponentContainer.LayoutConfig params = layout.getLayoutConfig();
        params.setMarginTop(0);
        layout.setLayoutConfig(params);
        tvLetter.setText(mDatas.get(firstVisibleItemPosition).letter);
        LogUtil.debug("progress",
            "mDatas.get(firstVisibleItemPosition).letter: " + mDatas.get(firstVisibleItemPosition).letter);
      }
      mLastFirstVisibleItem = firstVisibleItemPosition;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void onChange(int index, String c, ListContainer recyclerView) {
    if (recyclerView == null || mLetterMap == null) {
      return;
    }
    LogUtil.debug("sort", " onChange index: " + index + ", c: " + c);
    if (index == 0) {
      recyclerView.scrollTo(0);
      return;
    }
    int[] value = mLetterMap.get(c);
    if (value != null) {
      recyclerView.scrollTo(value[0]);
    }
  }

  /**
   * @param list Sort list
   * @return letters
   */
  public List<String> sortDatas(List<SortBean> list) {
    mLetterMap = new LinkedHashMap<>();
    if (list == null || list.size() <= 0) {
      return new ArrayList<>();
    }
    int count = list.size();
    for (int i = 0; i < count; i++) {
      SortBean bean = list.get(i);
      String pinyin = list.get(i).getIndex();
      String letter = TextTool.isNullOrEmpty(pinyin) ?
          list.get(i).getContent().substring(0, 1).toUpperCase() : pinyin.toUpperCase();
      // 正则表达式，判断首字母是否是英文字母/数字/其他
      if (letter.matches("[0-9]")) {
        letter = "☆";
      } else if (!letter.matches("[A-Z]")) {
        letter = "#";
      }
      bean.pinyin = pinyin;
      bean.letter = letter;
      bean.isLetter = false;
    }
    Collections.sort(list, new PinyinComparator());
    String key = null;
    int[] value = null; // is[0]:thisSectionPosition, is[1]:nextSectionPosition
    for (int i = 0; i < count; i++) {
      SortBean b = list.get(i);
      if (!TextTool.isEqual(key, b.letter)) {
        key = b.letter;
        b.isLetter = true;
        if (value != null) {
          value[1] = i;
        }
        value = new int[]{i, -1};
        mLetterMap.put(key, value);
      }
    }
    mDatas = list;
    LogUtil.debug("sort",
        " mDatas: " + mDatas.toString() + ", mLetterMap: " + mLetterMap.toString());
    return getLetters(mLetterMap);
  }

  private List<String> getLetters(Map<String, int[]> letterMap) {
    if (letterMap == null) {
      return new ArrayList<>();
    }
    List<String> letters = new ArrayList<>();
    for (Map.Entry<String, int[]> entry : letterMap.entrySet()) {
      letters.add(entry.getKey());
    }
    return letters;
  }
}
